package com.neuedu.vuejsserver.controller;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 项目：      jweb
 * 类名:       BaseController
 * 创建时间：  2023/11/29 16：23
 * 描述 :
 * 作者 :     张金山
 * QQ :     314649444
 * Site:      https://jshand.gitee.io
 */
public abstract class BaseController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String type = req.getParameter("_type");
        if(Objects.isNull(type) || "null".equals(type) || "".equals(type)){
            type = "list";
        }

        //如果不满足上述 条件   type: test    test()
        //反射
        Method declaredMethod = null;
        try {
            declaredMethod = this.getClass().getDeclaredMethod(type, HttpServletRequest.class, HttpServletResponse.class);
            declaredMethod.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }


    protected void writeJSON(HttpServletResponse resp, Object obj) throws IOException {
        String json = JSON.toJSONString(obj);
        resp.setContentType("application/json;charset=utf-8");

        PrintWriter writer = resp.getWriter();
        writer.write(json);
        writer.flush();
        writer.close();
    }



    protected abstract void list(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException;
    protected abstract void save(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException;
    protected abstract void queryById(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException;
    protected abstract void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;
    protected abstract void deleteById(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException;


}
